
package org.apache.mina.common.support;

import java.net.SocketAddress;
import java.util.Set;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.IoFilterChainBuilder;
import org.apache.mina.common.IoService;
import org.apache.mina.common.IoServiceListener;
import org.apache.mina.common.IoSession;

/**
 * Base implementation of {@link IoService}s.
 * 
 * IoService的基本实现类
 */
public abstract class BaseIoService implements IoService {
    /**
     * Current filter chain builder.
     * 
     * 当前过滤链的创建者。
     */
    private IoFilterChainBuilder           filterChainBuilder = new DefaultIoFilterChainBuilder();

    /**
     * Maintains the {@link IoServiceListener}s of this service.
     * 
     * 维护此服务的IoServiceListener。
     */
    private final IoServiceListenerSupport listeners;

    protected BaseIoService() {
        this.listeners = new IoServiceListenerSupport();
    }

    public IoFilterChainBuilder getFilterChainBuilder() {
        return filterChainBuilder;
    }

    public void setFilterChainBuilder(IoFilterChainBuilder builder) {
        if (builder == null) {
            builder = new DefaultIoFilterChainBuilder();
        }
        filterChainBuilder = builder;
    }

    public DefaultIoFilterChainBuilder getFilterChain() {
        if (filterChainBuilder instanceof DefaultIoFilterChainBuilder) {
            return (DefaultIoFilterChainBuilder) filterChainBuilder;
        } else {
            throw new IllegalStateException(
                    "Current filter chain builder is not a DefaultIoFilterChainBuilder.");
        }
    }

    public void addListener(IoServiceListener listener) {
        getListeners().add(listener);
    }

    public void removeListener(IoServiceListener listener) {
        getListeners().remove(listener);
    }

    public Set<SocketAddress> getManagedServiceAddresses() {
        return getListeners().getManagedServiceAddresses();
    }

    public Set<IoSession> getManagedSessions(SocketAddress serviceAddress) {
        return getListeners().getManagedSessions(serviceAddress);
    }

    public boolean isManaged(SocketAddress serviceAddress) {
        return getListeners().isManaged(serviceAddress);
    }

    protected IoServiceListenerSupport getListeners() {
        return listeners;
    }
}
